<?php
declare(strict_types=1);

namespace App\AdminApi\Module\Admin\Search;

use App\AdminApi\Module\Admin\Service\LoginLogService;
use App\Common\Query\Query;
use App\Sys;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Zms\Basics\BasicsSearch;
use Zms\Excel\Export;
use Zms\Unit\Is;

class LoginLogSearch extends BasicsSearch
{
    public function query(): Builder
    {
        $query = Sys::container(LoginLogService::class)->query();
        return $query
            ->when(isset($this->where['os']) && Is::notEmpty($this->where['os']), function (Builder $query) {
                $query->where('os', $this->where['os']);
            })
            ->when(isset($this->where['ip']) && Is::notEmpty($this->where['ip']), function (Builder $query) {
                Query::IpSearch($query, 'ip', $this->where['ip']);
            })
            ->when(isset($this->where['browser']) && Is::notEmpty($this->where['browser']), function (Builder $query) {
                $query->where(['browser' => $this->where['browser']]);
            })
            ->when(isset($this->where['time']) && Is::notEmpty($this->where['time']), function (Builder $query) {
                Query::TimeRangeSearch($query, '`time`', $this->where['time']);
            })
            ->when(isset($this->where['user_id']) && Is::notEmpty($this->where['user_id']), function (Builder $query) {
                Query::EqualOrInSearch($query, 'user_id', $this->where['user_id']);
            })
            ->orderByRaw($this->order);
    }


    public function export(string $filename): array
    {
        $excel = new Export(Sys::getAssetsPath('/export'));
        $excel->setFileName($filename, true);
        $excel->setColumn(['行为', '请求地址', '操作IP', '用户组', '应用标识', '时间', '状态', '浏览器', '操作人']);
        $this->query()->chunk(200, function (Collection $users) use (&$excel) {
            foreach ($users->toArray() as $item) {
                $excel->appendData([
                    $item['name'],
                    "[{$item['method']}]:{$item['url']}",
                    $item['ip'],
                    $item['guard'],
                    $item['app'],
                    date("Y-m-d H:i:s", $item['time']),
                    $item['status'] ? '成功' : '失败',
                    $item['browser'],
                    $item['user']['nickname'] ?? '',
                ]);
            }
        });
        $path = $excel->save();
        return ['file' => $path, 'url' => Sys::getAssetsUrl($path)];
    }
}